<?php

namespace app\common\controller;
use think\Controller;

/**
 * 微信
 */
class WeiXin extends Controller
{
    protected $WX_APPID = 'wx6f8f0af9f1aa443a';//微信appid
    protected $WX_APPSECRET = 'f5a3d356ced0a028c91260222500d088';//微信秘钥
    protected $openid = "";//当前用户openid

    //接入微信验证签名
    public function signature()
    {   
        // file_put_contents("signature.txt",'进入'.PHP_EOL,FILE_APPEND);
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'weixin';
        $tmpArr = array($token,$timestamp,$nonce);
        sort($tmpArr,SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        // file_put_contents("signature.txt","signature:".$signature."  --nonce:".$nonce."  --timestamp:".$timestamp."  --tmpStr".$tmpStr."".PHP_EOL,FILE_APPEND);
        if($tmpStr==$signature&&isset($_GET['echostr'])){
            // file_put_contents("signature.txt",'if进入'.PHP_EOL,FILE_APPEND);
            echo $_GET['echostr'];
            exit;
        }
        if(!isset($_GET['echostr'])){
            // file_put_contents("signature.txt",'else进入'.PHP_EOL,FILE_APPEND);
            //逻辑操作
            $this->responseMsg();
        }
    }
    /**
     * 回复消息
     * @return [type] [description]
     */
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        file_put_contents("signature.txt","postStr:".$postStr."".PHP_EOL,FILE_APPEND);
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            $openid = $postObj->FromUserName;//用户openid
            $this->openid = $openid;
            session('openid',$openid);
            //用户发送的消息类型判断
            switch ($RX_TYPE)
            {
                case "text":    //文本消息
                    $result = $this->receiveText($postObj);
                    break;
                case "image":   //图片消息
                    $result = $this->receiveImage($postObj);
                    break;

                case "voice":   //语音消息
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":   //视频消息
                    $result = $this->receiveVideo($postObj);
                    break;
                case "location"://位置消息
                    $result = $this->receiveLocation($postObj);
                    break;
                case "link":    //链接消息
                    $result = $this->receiveLink($postObj);
                    break;
                case "event":  //事件
                    if(trim($postObj->Event)=="subscribe"){//关注事件
                        file_put_contents("signature.txt",'subscribe:进入'.PHP_EOL,FILE_APPEND);
                        $this->register();
                    }else{//取消关注

                    }
                    // $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    /*
     * 接收文本消息
     */
    private function receiveText($object)
    {
        $content = "你发送的是文本，内容为：".$object->Content;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收图片消息
     */
    private function receiveImage($object)
    {
        $content = "你发送的是图片，地址为：".$object->PicUrl;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收语音消息
     */
    private function receiveVoice($object)
    {
        $content = "你发送的是语音，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收视频消息
     */
    private function receiveVideo($object)
    {
        $content = "你发送的是视频，媒体ID为：".$object->MediaId;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收位置消息
     */
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 接收链接消息
     */
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    /*
     * 回复文本消息
     */
    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }


    /** 
     * 获取接口调用凭证 access_token
     * @return [type] [description]
     */
    public function get_access_token(){
        file_put_contents("signature.txt",'get_access_token:凭证进入'.PHP_EOL,FILE_APPEND);
        $data = json_decode(file_get_contents("access_token.json"));
        file_put_contents("signature.txt",'get_access_token:凭证过期时间进入'.$data->expire_time.PHP_EOL,FILE_APPEND);
        if($data->expire_time < time()){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->WX_APPID ."&secret=".$this->WX_APPSECRET;
            file_put_contents("signature.txt",'get_access_token:url重新请求进入'.$url.PHP_EOL,FILE_APPEND);
            $curl_data = ihttp_get($url);
            file_put_contents("signature.txt",'get_access_token:重新请求curl_data'.$curl_data.PHP_EOL,FILE_APPEND);
            $res = json_decode($curl_data);
            $access_token = $res->access_token;
            file_put_contents("signature.txt",'get_access_token:重新请求获取'.$access_token.PHP_EOL,FILE_APPEND);
            if($access_token){
                $data->expire_time = time() + 3600;
                $data->access_token = $access_token;
                $fp = fopen("access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }else{
            $access_token = $data->access_token;
        }
        return $access_token;
    }


    /**
     * 用户注册
     */
    public function register(){
        $access_token = $this->get_access_token();
        $openid = $this->openid;
        if($openid){
            $openid = session('openid');
        }
        file_put_contents("signature.txt",'access_token:进入'.$access_token.PHP_EOL,FILE_APPEND);
        file_put_contents("signature.txt",'openid:进入'.$openid.PHP_EOL,FILE_APPEND);
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        file_put_contents("signature.txt",'register:获取用户信息'.$url.PHP_EOL,FILE_APPEND);
        $map['wechat_name']  = array('neq','');
        $map1['headimgurl']  = array('neq','');
        $re = db('member')->where(['openid'=>$openid])->where($map)->where($map1)->find();
        if(!$re){
            $curl_data = ihttp_get($url);
            $res = json_decode($curl_data,true);
            //dump($res);exit;
            if($res['sex'] == 1){
                $gender = 0;//男
            }else{
                $gender = 1;//女
            }
            $user = [
                'wechat_name' => $res['nickname'],
                'gender' => $gender,
                'headimgurl' => $res['headimgurl'],
                'openid' => $res['openid'],
                'create_time' => $res['subscribe_time'],
            ];
            file_put_contents("signature.txt",'user:进入'.json_encode($user).PHP_EOL,FILE_APPEND);
            $re1 = db('member')->where(['openid'=>$openid])->find();
            if($re1){
                db('member')->where(['openid'=>$openid])->update($user);
            }else{
                db('member')->insert($user);
            }
        }
    }

    /**
     * 用户网页授权 获取code
     */
    public function get_author($callback="http://fz.58zltc.com/index/frog/get_code"){
        $redirect_uri = $callback;
        $state = md5(uniqid(rand(),TRUE));//唯一ID标识符绝对不会重复
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->WX_APPID."&redirect_uri=".urlEncode($redirect_uri)."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
        file_put_contents("signature.txt",'get_author 进入:'.date("Y-m-d:H:i:s",time()).$redirect_uri.PHP_EOL,FILE_APPEND);
        file_put_contents("signature.txt",'get_author url进入:'.date("Y-m-d:H:i:s",time()).$url.PHP_EOL,FILE_APPEND);
        header("Location:".$url);exit;
    }

    /**
     * code获取access_token openid 
     */
    public function get_author_openid($code){
        file_put_contents("signature.txt",'session(openid):'.date("Y-m-d:H:i:s",time()).session('openid').PHP_EOL,FILE_APPEND);
        if(session('openid')==''){
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->WX_APPID."&secret=".$this->WX_APPSECRET."&code=".$code."&grant_type=authorization_code";
            $curl_data = ihttp_get($url);
            $res = json_decode($curl_data);
            //dump($res);exit;
            //$access_token = $res->access_token;
            $openid = $res->openid;
            session('openid',$openid);
            $this->openid = $openid;
            file_put_contents("signature.txt",'author_access_token：网页授权获取'.$res->access_token.PHP_EOL,FILE_APPEND);
            //file_put_contents("signature.txt",'author_openid:获取'.$openid.PHP_EOL,FILE_APPEND);
        }else{
            $openid = session('openid');
        }
        $uid = db('member')->where(['openid'=>$openid])->value('id');
        if(!$uid){
            $data = [
                'openid' => $openid,
                'create_time' => time(),
            ];
            db('member')->insert($data);
            $uid = db('member')->where(['openid'=>$openid])->value('id');
        }
        session('uid',$uid);
        return $openid;    
    }

    /** 
     * frog 获取用户uid
     */
    public function get_frog_uid(){
        $openid = session('openid');
        if(!$openid){
            $url = 'http://'.$_SERVER['HTTP_HOST'].'/index/frog/index';
            header("Location:".$url);exit;
        }else{
            $uid = db('member')->where(['openid'=>$openid])->value('id');
            if(!$uid){
                $data = [
                    'openid' => $openid,
                    'create_time' => time(),
                ];
                db('member')->insert($data);
                $uid = db('member')->where(['openid'=>$openid])->value('id');
            }
            session('uid',$uid);
        }
        return $uid;
    }

}
